<?php
session_start(); //Starts the session in php
//Things that this will do:
//1. Check if user has logged in - Case1
//2. Check if the login is proper - Case2
//3. Don't go anywhere if login is improper or user has not logged in anymore
//   or has logged out - Case3

include('config.php');

if(isset($_SESSION['userNum'])){
	$case = "case1";
	$userNum = $_SESSION['userNum'];// sets the session to the userNum variable
	$ifLoginIsSingle = checkSessionID($_SESSION['sid'],$userNum,$server,$user,$pass,$db);
		
		if($ifLoginIsSingle == "False"){
			session_destroy(); 
			header('Location: home.php');
		}
		
	$_SESSION['server'] = $server;
	$_SESSION['user'] = $user;
	$_SESSION['pass'] = $pass;
	$_SESSION['db'] = $db;
	$_SESSION['title'] = $title;
	$pageTitle = $_SESSION['title'];
	
	$_SESSION['loginCount'] = 0;
	
}else{

	$isLoginCorrect = checkLogin($_POST["uname"],$_POST["password"],$server,$user,$pass,$db); //Check login details
	if($isLoginCorrect == "True"){ // If login is correct, sets the session variable.
		$_SESSION['userNum']=$_POST['uname']; 
		$userNum = $_SESSION['userNum']; // The userNum variable will be used to refer to the session variable
		insertAllInfoToSessions($userNum,$server,$user,$pass,$db);// Insert all voter info to session variables
		//Add the server information to the session variables
		$_SESSION['server'] = $server;
		$_SESSION['user'] = $user;
		$_SESSION['pass'] = $pass;
		$_SESSION['db'] = $db;
		$_SESSION['title'] = $title;
		$pageTitle = $_SESSION['title'];
		
		$_SESSION['loginCount'] = 0;
		
		$case = "case2";
	}else{ //else don't do anything
		$_SESSION['loginCount'] = $_SESSION['loginCount'] + 1;
		$loginCount = $_SESSION['loginCount'];
		$case = "case3";
	}
}?>
<html>
<head>
<title>
<?php
	if(($case == "case1") || ($case == "case2")){ //If user has logged in succesfully, show this title
	echo "Welcome - ".$pageTitle."";
	}else{ // If it is not going anywhere, use this title instead
	echo "Login in to ".$title."";
	}
?>
</title>

<script type="text/JavaScript">
<!--
function popup() {
alert("Hello World")
}
//-->
</script>

<style type="text/css">
.style1 {
	border-collapse: collapse;
}
.style2 {
	border-collapse: collapse;
	background-image: url('images/bg.png');
}
a {
	color: #FFFFFF;
}
</style>
</head>
<body style="background-image:url('images/bg_blue.jpg')">
<div style="position:absolute;left:75px;top: 0px">
<table width = '810px' border="0" cellspacing="0" cellpadding="0">
<?php include("newsBanner.php"); ?>
</table>
<font face = "Arial">
<table style="width: 810px; height: 104px" border="0" cellspacing="0" cellpadding="0" class="style1">
<?php
if($case == "case1" || $case == "case2"){
include("menuButtons.php");
}else{
echo "<tr>";
echo "<td colspan='6' style='height: 104px'>";
echo "<img src='images/header.png'></td>";
echo "</tr>";
echo "</table><table style='width: 810px' background='images/menu.png' cellspacing='0' cellpadding='0' border='0'><tr><td width = '810px' height = '40px'></td></tr>";
}
?>
</table>
<table style="width: 810px;" cellspacing="0" cellpadding="0" class="style2">
<tr>
<td style="height: 76px; width: 28px;"></td>
<td style="height: 76px" width="808px">
<?php
//Check the case based from the steps taken above
if($case == "case1"){ //User has logged in last time - Use session variables
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	$result = mysql_query("SELECT * FROM voters where voter_num =".$userNum) or die(mysql_error());  //Get all information from voter
	while($row = mysql_fetch_array( $result )){ //Show information
	echo "<br><h2>Welcome ".$row['voter_fname']." ".$row['voter_lname']."</h2>";
	echo "This is the APC voting system<br>";
	echo "You can view the candidates in the Candidates page<br>";
	echo "or you can vote already in the Vote page<br>";
	echo "<br><br><br><strong>Voter Information</strong><br>";
	echo "<font size = '2px'>";
	echo "Voter Number: ".$row['voter_num'];
	echo "<br>Account Type: ".$row['voter_permission'];
	
	}
}
if($case == "case2"){ //user logged in, login is already correct
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	$result = mysql_query("SELECT * FROM voters where voter_num =".$_POST["uname"]." and voter_pass =".$_POST["password"])
	or die(mysql_error()); 
		while($row = mysql_fetch_array( $result )){ // Show information
		echo "<br><h2>Welcome ".$row['voter_fname']." ".$row['voter_lname']."</h2>";
		echo "This is the APC voting system<br>";
		echo "You can view the candidates in the Candidates page<br>";
		echo "or you can vote already in the Vote page<br>";
		echo "<br><br><br><strong>Voter Information</strong><br>";
		echo "<font size = '2px'>";
		echo "Voter Number: ".$row['voter_num'];
		echo "<br>Account Type: ".$row['voter_permission'];
		echo "</font>";	
		}
	}		
if($case == "case3"){ //User logged out, or user is not logged in already
		
		echo "<br><h4> Please login here </h4>";
		if($loginCount>1){ echo "<font color='red' size='2'>Invalid Voter Number or Password</font>"; }
		echo "<form action='home.php' method='POST'>";
		echo "<table cellpadding='4'>";
		echo "<tr><td align='right'>Voter Number:</td> <td><input type='text' name='uname' size='30'></td></tr><tr>";
		echo "<td align='right'>Password: </td><td><input name = 'password' type = 'Password' Size = '30'></td></tr><tr>";
		echo "<td></td><td align='right'><input type='submit' value='Login' ></td>";
		echo "</tr></table></form>";
		echo "<br><br>Eto ung accounts - Chik it out!<br>";
		mysql_connect($server,$user,$pass) or die(mysql_error());
		mysql_select_db($db) or die(mysql_error());
		$result = mysql_query("SELECT * FROM voters where voter_permission='Voter'") or die(mysql_error());  //Get all information from voter
		while($row = mysql_fetch_array( $result )){ 
		echo "<br>".$row['voter_fname']." Voter Number: ".$row['voter_num']." Pass: ".$row['voter_pass'];
		}
}
//Function checkLogin
// Function accepts the ff parameters:
// userNumber = input voter number
// userPass = input password
// sver,usr,passwd,dbase - information for database connection
function checkLogin($userNumber,$userPass,$sver,$usr,$passwd,$dbase){
	$userNumber = (int)$userNumber;
	if($userNumber == "" || $userNumber < 0){ //userNumber doesn't exist - happens when user has logged out, set up a invalid login
	$userNumber = "0000";
	$userPass = "0000";
	}
		mysql_connect($sver,$usr,$passwd) or die(mysql_error());
		mysql_select_db($dbase) or die(mysql_error());
		$result = mysql_query("SELECT * FROM voters where voter_num= ".$userNumber." AND voter_pass=".$userPass) //check whether an entry exist w/ the given username and password
		or die(mysql_error());
		while($row = mysql_fetch_array( $result )){
		if($row['voter_num'] < 0){
		return "False"; // if there are no results, return false
		}else{
		return "True"; // else, return true
}}}

//Function insertAllInfoToSessions()
// -Gets all voter info, then puts it in 
// session variables to be accessed at any page.
function insertAllInfoToSessions($userNumber,$sver,$usr,$passwd,$dbase){
mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

$randomSessionId = uniqid();
$_SESSION['sid'] = $randomSessionId;

mysql_query("UPDATE voters SET voter_current_session =  '".$randomSessionId ."' WHERE voter_num = '".$userNumber."'");	
$info = mysql_query("Select * from voters where voter_num = '".$userNumber."'");
	while($infoLine = mysql_fetch_array($info)){
	$_SESSION['voter_permission'] = $infoLine['voter_permission'];
	$_SESSION['voter_lname'] = $infoLine['voter_lname'];
	$_SESSION['voter_fname'] = $infoLine['voter_fname'];
	}
}

//Function checkSessionID()
// -Checks if session in db is same in the session in browser
// If not, it logs out
function checkSessionID($sid,$uname,$sver,$usr,$passwd,$dbase){
mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

	$querySession = mysql_query("SELECT voter_current_session from voters WHERE voter_num = '".$uname."'");	

		while($sessionInDB = mysql_fetch_array($querySession)){
		$loggedSession = $sessionInDB['voter_current_session'];
		}

	if($_SESSION['sid'] == $loggedSession){
	return "True";
	}else{
	return "False";
	}	
}
?>
</td>
</tr>
</table>
<br><br><br><br><br>
</div>
<div style="position:fixed;left:72px;bottom: -5px">
<table>
<tr>
<td width="8px" colspan="2" style="background-image:url('images/end.png')"></td>
</tr>
</table>
</div>
<div style="position:fixed;right:72px;bottom: 0px">
<a href="http://www.freedomain.co.nr/" target="_blank">
<img src="http://zurmsna.4u.com.ru/but1.gif" width="88" height="31" border="0" alt=".CO.NR Free Domain" /></a>
</div>
</body>
</html>
